import Selector from "components/selector";
import moment from 'moment'

export const hasValue = (field, value) => {
  if(field.hasValue)
    return field.hasValue(value);
  return (value instanceof Array) ? value.length > 0 : value;
};

export const formatValue = (source, searchForm) => {
  let values = {...source};
  searchForm
    .filter(field => field.component === 'Selector' && !field.props.entity && values[field.id])
    .map(field => {
      let selectorKey = (field.props.selectorItem || Selector.getSelectorData(field.props.type)).key;
      values[field.id] = values[field.id][selectorKey];
    });
  //Chooser、Searcher onlyNeed模式参数处理
  searchForm
    .filter(field =>
      ['Chooser', 'Searcher'].indexOf(field.component) > -1 &&
      field.props.onlyNeed &&
      hasValue(field, values[field.id])
    ).map(field => {
    if(values[field.id] instanceof Array)
      values[field.id] = values[field.id].map(item => item[field.props.onlyNeed]);
    else
      values[field.id] = values[field.id][field.props.onlyNeed];
  });
  //按照字段的parser在结果对象里插入参数，删除原有Id
  searchForm
    .filter(field => field.parser)
    .map(field => {
      let valueFromField = field.parser(values[field.id]);
      values = Object.assign(values, valueFromField);
      if(!valueFromField || !(field.id in valueFromField))
        delete values[field.id];
    });
  return values;
};

export const stringifyJSONValue = (values, searchForm, source) => {
  return searchForm.map(field => {
    let value = values[field.id];
    let criteriaValue;
    if(!hasValue(field, value))
      criteriaValue = JSON.stringify(null);
    else if(field.JSONFormatter)
      criteriaValue = field.JSONFormatter(value, hasValue);
    else if(moment.isMoment(value))
      criteriaValue = JSON.stringify(`_moment:${value.format()}`);
    else if(value instanceof Array && value.length > 0) {
      criteriaValue = value.map(item => {
        if(item && moment.isMoment(item))
          return `_moment:${item.format()}`;
        if(!item)
          return null;
        return item
      });
      if(field.JSONObjectFormatterParams) {
        criteriaValue = criteriaValue.map(item => {
          let target = {};
          field.JSONObjectFormatterParams.map(param => {
            target[param] = item[param];
          });
          return target;
        })
      }
      criteriaValue = JSON.stringify(criteriaValue);
    } else if(value instanceof Object && field.JSONObjectFormatterParams) {
      let target = {};
      field.JSONObjectFormatterParams.map(param => {
        target[param] = value[param];
      });
      criteriaValue = JSON.stringify(target)
    } else {
      criteriaValue = JSON.stringify(value);
    }
    let result = {
      criteriaName: field.id,
      criteriaValue
    };
    let sourceItem = source.find(s => s.criteriaName === field.id);
    if(sourceItem)
      result.id = sourceItem.id;
    return result;
  })
};

const checkMomentAndParse = value => {
  if(value && typeof value === 'string' && value.startsWith('_moment:'))
    return moment(value.substr(8, value.length - 1));
  else
    return value;
};

export const parseJSONValue = (queryValueDTOList, searchForm) => {
  let result = {};
  queryValueDTOList.map(dto => {
    let value = dto.criteriaValue;
    let field = searchForm.find(item => item.id === dto.criteriaName);
    if(field && field.JSONParser)
      value = field.JSONParser(value);
    else {
      value = JSON.parse(value);
      value = checkMomentAndParse(value);
      if(value && value instanceof Array && value.length > 0) {
        value = value.map(checkMomentAndParse)
      }
    }
    result[dto.criteriaName] = value;
  });
  return result;
};
